import services from '@/services/demo';
import {
  PageContainer,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Divider, message, Modal } from 'antd';

const { queryArticleList } = services.UserController;
const ArticleList: React.FC<unknown> = () => {
  const [modal, contextHolder] = Modal.useModal();
  const handleEdit = (record: API.Article) => {
    console.log(record);
    history.push(`/article/edit/${record.id}`);
  };
  const handleDelete = async (record: API.Article) => {
    const { success, errorMessage } =
      await services.UserController.deleteArticle({
        articleId: record.id,
      });
    if (success) {
      message.success('删除成功');
    } else {
      message.error(errorMessage);
    }
  };
  const columns: ProColumns<API.Article>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Divider type="vertical" />
          <a
            onClick={async () => {
              const confirmed = await modal.confirm({ title: '确认删除？' });
              if (confirmed) {
                handleDelete(record);
              }
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'CRUD 示例',
      }}
    >
      <ProTable<API.Article>
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
        request={async (params, sorter, filter) => {
          const { data, success } = await queryArticleList({
            ...params,
            // FIXME: remove @ts-ignore
            // @ts-ignore
            sorter,
            filter,
          });
          return {
            data: data?.data || [],
            success,
            total: data?.total,
          };
        }}
      ></ProTable>
      {contextHolder}
    </PageContainer>
  );
};

export default ArticleList;
